<?php
/*******************************************************
*
* Page:   app_object.class
* Author:  Matthew Sturges (matt@matthewsturges.com)
* Purpose: Base class for creating persistent data objects
* Created: 06/29/05
* Version: 2.0
*
* Modified:
*   12/28/07 MF - Modified insert function to mimic the way the update function operates, in that only
*                 predefined fields will be specified in the insert SQL statement, adhoc fields are ignored.
*
*   12/11/07 CK - This is the updated version containing new method accumulated over time from building 
*                 and updating several applictions.  The only significant changes to the original methods 
*                 are to the sql_safe and sql_unsafe functions.  Those used to fix date fields, but now only 
*                 deal with escaping quotes.
*
*******************************************************/

class app_object {
    var $fields;
    var $values;
    var $table;
    var $id_field;
    var $id_value;

	function app_object($fields = array(), $table = '', $id_field = ''){
        $this->fields = $fields;
        $this->table = $table;
        $this->id_field = $id_field;
        foreach ($this->fields as $field){
            $this->values[$field] = '';
        }
    }
    ////////////////////////////////////////////////////////////////////////////////////////
	function load($obj_id){
	    //  loads a whole record given the PK
        if ($obj_id === ""){
            return;
        }
        $this->id_value = $obj_id;
        $query = "SELECT ";
        $query.= implode(',', $this->fields);
        $query.= " FROM " . $this->table . " WHERE " . $this->id_field . " = '" . $this->id_value . "'";
        $result = app_data::mysql_query($query);
        if (mysql_num_rows($result) > 0) {
            $this->values = mysql_fetch_array($result, MYSQL_ASSOC);
        } else {
            $this->values = array_fill(0, count($this->fields), null);
        }
        $this->sql_unsafe();
	}//end function load
	
	////////////////////////////////////////////////////////////////////////////////////////
	function load_field($obj_id,$field) {
        //  loads a single field given a PK and field name
        
        if ($obj_id === "" || $field == ""){
            return;
        }
        $query = "SELECT $field";
        $query.= " FROM " . $this->table . " WHERE " . $this->id_field . " = '$obj_id'";
        $result = app_data::mysql_query($query);
        
        if ( mysql_num_rows($result) == 0) {
            return "-1";
        }
        $row=mysql_fetch_array($result);
        return stripslashes($row[$field]);
    } // end function load_field


    ////////////////////////////////////////////////////////////////////////////////////////
    function load_table($sortby='', $sortorder="ASC") {
        // loads a whole table into a query response
        if ($sortby=='') {
            $sortby=$this->id_field;
        }
        $query = "SELECT *";
        $query.= " FROM " . $this->table;
        $query.= " ORDER BY " . $sortby . " $sortorder";
        $result = app_data::mysql_query($query);
        return $result;
    }

    ////////////////////////////////////////////////////////////////////////////////////////
	function load_from_request(){
        $this->id_value = $_REQUEST[$this->id_field];
        foreach ($this->fields as $field) {
            $this->values[$field] = $_REQUEST[$field];
		}//end foreach
	}//end function load_from_request
	
    ////////////////////////////////////////////////////////////////////////////////////////	
	function update_from_request(){
	    if ($this->id_value == '') {
   	  	    $this->id_value = trim ($_REQUEST[$this->id_field]);
   	    }
	
        foreach ($this->fields as $field) {
            if ( strlen($_REQUEST[$field]) > 0) {
                $this->values[$field] = $_REQUEST[$field];
            }
            else {
                if ($this->id_value == '') {
                    $this->values[$field] = '';
                }
            }
		}//end foreach
	}//end function load_from_request

    ////////////////////////////////////////////////////////////////////////////////////////
	function save(){
        if ($this->id_value != ""){
            $this->update();
        } else {
            $this->insert();
        }//end if

    }//end function save()

    ////////////////////////////////////////////////////////////////////////////////////////
	function update(){
		$this->sql_safe();
        $query = "UPDATE " . $this->table . " SET ";
        foreach ($this->fields as $field){
            $value = $this->values[$field];
            $query.= "" . $field . " = '" . $value . "', ";
        }//end foreach
        $query = substr($query, 0, -2); //Remove the trailing ", "
        $query.= " WHERE " . $this->id_field . " = '" . $this->id_value . "'";

        app_data::mysql_query($query);
		$this->sql_unsafe();
    }// end function update()

    ////////////////////////////////////////////////////////////////////////////////////////
	function insert(){
		$this->sql_safe();

		$query = "INSERT INTO " . $this->table . "(`";
        $query.= implode('`, `', $this->fields);
        $query.= "`) VALUES (";
        
        foreach ($this->fields as $field) { // foreach loop looks only at predefined fields for the object
        	$value = $this->values[$field];
        	$query.= "'$value', ";
        }
        $query = substr($query, 0, -2); //Remove the trailing ", 
		$query.= ")";
       
        app_data::mysql_query($query);
        $this->id_value = mysql_insert_id();
		$this->sql_unsafe();
    } // end function insert()

    ////////////////////////////////////////////////////////////////////////////////////////
	function sql_safe(){
    
        foreach ($this->fields as $field){
            if (!is_null($this->values[$field])){
                $this->values[$field] = addslashes(stripslashes($this->values[$field]));
            }
        }// end foreach

    }//end function sql_safe()

    ////////////////////////////////////////////////////////////////////////////////////////
	function sql_unsafe(){
       
       foreach ($this->fields as $field){
            if (!is_null($this->values[$field])){
                $this->values[$field] = stripslashes($this->values[$field]);
            }
        }// end foreach

	}//end function sql_unsafe()
	
    ////////////////////////////////////////////////////////////////////////////////////////
	function html_safe(){
        // use before adding object fields to html attributes such as value=""
        // this converts all quotations to html entities (e.g. &quot;)
        foreach ($this->fields as $field){
            if (!is_null($this->values[$field])){
                $this->values[$field] = htmlentities($this->values[$field],ENT_QUOTES);
            }
        }// end foreach

    }//end function html_safe()
    
    ////////////////////////////////////////////////////////////////////////////////////////
    function html_unsafe(){
        // converts html entities (e.g. &quot;) back to the ASCII character
        foreach ($this->fields as $field){
            if (!is_null($this->values[$field])){
                $this->values[$field] = html_entity_decode($this->values[$field],ENT_QUOTES);
            }
        }// end foreach

    }//end function html_unsafe()

    ////////////////////////////////////////////////////////////////////////////////////////
    function delete($obj_id){
        $query = "DELETE FROM " . $this->table . " WHERE " . $this->id_field . " = '" . $obj_id . "'";
        app_data::mysql_query($query);
    }
    
    
    // Note that the functions below only set fields stored in the values[] array
    // so the id_value and the table_name won't get set
    // if needed could easily be expanded at some point
    
    
    
    ////////////////////////////////////////////////////////////////////////////////////////
    function save_to_session($prefix="sess_") {
         // saves the object values hash to a corresponding SESSION hash
         // The field names are given a prefix so that this data wont interfere with other session data with the same fields
         // like from from a search form
        foreach ($this->fields as $field) {
            $sess_fieldname = $prefix.$field;
            $_SESSION[$sess_fieldname] = $this->values[$field];
        }   
    } // end function save_to_session

    ////////////////////////////////////////////////////////////////////////////////////////
    function load_from_session($prefix="sess_") {
         // loads the object values hash from a corresponding SESSION hash
         // The field names are given a prefix so that this data wont interfere with other session data with the same fields
         // like from from a search form, se we strip 'em here     
        foreach ($this->fields as $field) {
     
            $sess_fieldname = $prefix.$field;
            $this->values[$field] = $_SESSION[$sess_fieldname];
        }   
    } // end function load_from_session
    
    ////////////////////////////////////////////////////////////////////////////////////////
    function wipe_from_session($prefix="sess_") {
         // wipes the object values hash from a corresponding SESSION hash    
        foreach ($this->fields as $field) {
     
            $sess_fieldname = $prefix.$field;
            unset($_SESSION[$sess_fieldname]);
        }   
    } // end function load_from_session

    ////////////////////////////////////////////////////////////////////////////////////////
    function hide_in_form() {
         // writes all object fields to hidden form elements and hides the quotes
        $this->html_safe();
        foreach ($this->fields as $field) {
            // would just escape the quotes, but html is too dumb for that
            
            echo '<input type="hidden" name="'.$field.'" value="'.$this->values[$field].'"/>'."\n";
        }
        $this->html_unsafe();
    } // end function hide_in_form
    
    ////////////////////////////////////////////////////////////////////////////////////////
    function load_from_hidden() {
         // recovers all object fields from hidden form elements and unhides the quotes
        foreach ($this->fields as $field) {
            $value = $_REQUEST[$field];
            $this->values[$field] = $value ;
        }
        $this->html_unsafe(); 
    } // end function hide_in_form

    ////////////////////////////////////////////////////////////////////////////////////////
    function strip() {
         // trims and removes slashes 
        foreach ($this->fields as $field) {
            $this->values[$field] = stripslashes(trim($this->values[$field]));
        }   
    } // end function strip


}//end app_object

?>